package today.rocky.boot.shiro.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/**
 * @author Rocky
 * @version 1.0
 * @date 2020/4/14 12:20
 */
@Controller
@Slf4j
public class LoginController {
	@GetMapping
	public String index(){
		return "redirect:login";
	}
	@RequestMapping("/add")
	public String add(){
		return "user/add";
	}

	@RequestMapping("/update")
	public String update(){
		return "user/update";
	}

	@RequestMapping("/toLogin")
	public String toLogin(){
		return "login";
	}

	@RequestMapping("/noAuth")
	public String noAuth(){
		return "noAuth";
	}

	/**
	 * 测试thymeleaf
	 */
	@RequestMapping("/testThymeleaf")
	public String testThymeleaf(Model model){
		//把数据存入model
		model.addAttribute("name", "黑马程序员");
		//返回test.html
		return "test";
	}


	@PostMapping("/login")
	public String login(String name, String password,Model model){
		Subject subject = SecurityUtils.getSubject();
		log.info("name:"+name+" password:"+password);
		UsernamePasswordToken token = new UsernamePasswordToken(name,password);

		try {

			subject.login(token);

			//登录成功
			//跳转到test.html
			return "redirect:/testThymeleaf";
		} catch (UnknownAccountException e) {
			//e.printStackTrace();
			//登录失败:用户名不存在
			log.info("用户名不存在");
			model.addAttribute("msg", "用户名不存在");
			return "login";
		}catch (IncorrectCredentialsException e) {
			//e.printStackTrace();
			//登录失败:密码错误
			log.info("密码错误");
			model.addAttribute("msg", "密码错误");
			return "login";
		}
	}



}
